package pure.engine.world 
{
	import flash.display.Sprite;
	import pure.engine.model.Model2D;
	import pure.engine.core.ns_despair;
	
	use namespace ns_despair;
	
	/**
	 * 图层融合
	 * [Author] - PURE
	 * 
	 * [Hint] - 保存与处理Layer，每个Monitor包含一个LayerFusion.
	 *          图层一旦加入，除非改变世界，否则不会消失...
	 */
public class LayerFusion extends Sprite 
{

	
	/**
	 * 渲染模型
	 * 
	 * [Param] - model  模型
	 */
	ns_despair function makeMirrorToLayer(model:Model2D):void
	{
		var layerIndex:int = model.m_layerIndex;
		var layer:Layer;
		var mirror:Mirror = model.createMirror();
		
		// 没有，生成图层，排序
		if (!m_layerMap[layerIndex])
		{
			layer = m_layerMap[layerIndex] = Layer.getLayer();
			m_layerIndexList.push(layerIndex);
			m_flushLayerIndexList.push(layerIndex);
		}
		else
		{
			layer = m_layerMap[layerIndex];
		}
		
		// 残像绑定模型，加入图层
		layer.addMirror(mirror);
		
		// 图层变脏
		if (!layer.m_dirty)
		{
			m_dirtyLayerIndexList[m_numDirty++] = layer;
			layer.m_dirty = true;
		}
	}
	
	
	/**
	 * 刷新
	 */
	ns_despair function flush():void
	{
		var i:int, len:int = m_flushLayerIndexList.length;
		var layerIndex:int, index:int;
		
		// 新加入图层
		m_layerIndexList.sort(Array.NUMERIC);
		m_flushLayerIndexList.sort(Array.NUMERIC);
		for (i = 0; i < len; i++)
		{
			layerIndex = m_flushLayerIndexList[i];
			index = m_layerIndexList.indexOf(layerIndex);
			this.addChildAt(m_layerMap[layerIndex], index);
		}
		m_flushLayerIndexList.length = 0;
		
		// 处理脏图层
		for (i = 0; i < m_numDirty; i++)
		{
			m_dirtyLayerIndexList[i].flush();
		}
		m_numDirty = m_dirtyLayerIndexList.length = 0;
	}
	
	
	/**
	 * 清空
	 * 
	 * [Hint] - 此方法一般在改变世界时使用.
	 */
	ns_despair function clear():void
	{
		var layer:Layer;
		
		for each(layer in m_layerMap)
		{
			layer.clear();
			this.removeChild(layer);
		}
		m_layerMap = { };
		m_layerIndexList.length = m_dirtyLayerIndexList.length = m_numDirty = 0;
	}
	
	
	/**
	 * 毁灭
	 */
	ns_despair function destroy():void
	{
		var layer:Layer;
		
		// 移除全部显示对象
		while (this.numChildren)
		{
			removeChildAt(0);
		}
		
		// 回收全部图层
		for each(layer in m_layerMap)
		{
			layer.recycle();
		}
		
		m_layerMap = null;
		m_layerIndexList = m_flushLayerIndexList = null;
		m_dirtyLayerIndexList = null;
	}
	
	
	
	
	//======================
	// Member
	//======================
	
		
	ns_despair var m_layerMap:Object = { };  // layerIndex : Layer
	
	ns_despair var m_layerIndexList:Array = [];  // 图层索引列表

	ns_despair var m_flushLayerIndexList:Array = [];  // 新加入图层索引列表

	ns_despair var m_dirtyLayerIndexList:Vector.<Layer> = new  Vector.<Layer>();  // 脏图层索引列表
	
	ns_despair var m_numDirty:int;  // 脏图层数量

	
	
}

}